package cn.itcast.nems.journal.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Assert;
import cn.itcast.ic.common.exception.v2.BizExceptionProducer;
import cn.itcast.nems.common.utils.WrapperUtil;
import cn.itcast.nems.journal.dto.JournalRenewalDiscountDTO;
import cn.itcast.nems.journal.service.JournalRenewalDiscountService;
import cn.itcast.nems.manager.util.CustomBeanUtil;
import cn.itcast.nems.studentrecord.dao.dataobject.JournalRenewalDiscountDO;
import cn.itcast.nems.studentrecord.dao.entity.JournalRenewal;
import cn.itcast.nems.studentrecord.dao.entity.JournalRenewalDiscount;
import cn.itcast.nems.studentrecord.dao.mapper.JournalRenewalDiscountMapper;
import cn.itcast.nems.studentrecord.dao.mapper.JournalRenewalMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Objects;

/**
 * @author 周伟
 */
@Service
@Slf4j
@RequiredArgsConstructor
public class JournalRenewalDiscountServiceImpl
        extends ServiceImpl<JournalRenewalDiscountMapper, JournalRenewalDiscount>
        implements JournalRenewalDiscountService {

    private final JournalRenewalMapper journalRenewalMapper;
    @Override
    public List<JournalRenewalDiscountDO> findListByClazzId(Integer clazzId) {
        JournalRenewal journalRenewal = journalRenewalMapper.selectOne(new WrapperUtil<JournalRenewal>().limitLaseOne("created_datetime").eq(JournalRenewal::getTargetClazzId, clazzId)) ;
        Assert.notNull(journalRenewal , BizExceptionProducer.serverError("clazzId: %s ,没有对应升级凭单",clazzId)) ;
        return getBaseMapper().findListByJournalRenewalId(journalRenewal.getId());
    }

    @Override
    public List<JournalRenewalDiscountDTO> findListByJournalRenewalId(String journalRenewalId) {
        List<JournalRenewalDiscountDO> renewalDiscountList= getBaseMapper().findListByJournalRenewalId(journalRenewalId);
        return CollectionUtil.isEmpty(renewalDiscountList) ? null :
                renewalDiscountList.stream().map(item -> {
                    JournalRenewalDiscountDTO discountDTO = CustomBeanUtil.copyProperties(item, new JournalRenewalDiscountDTO());
                    discountDTO.setDiscountAmount(Objects.nonNull(item.getDiscountAmount()) ?
                            BigDecimal.valueOf(item.getDiscountAmount()).divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP) :
                            BigDecimal.valueOf(0));
                    return discountDTO;
                }).sorted().toList();
    }
}
